<?php
namespace App\Http\Controllers\Auth;

use App\Jobs\GetMobileCityIdJob;
use App\Jobs\SendSystemMsgJob;
use App\Jobs\UpdateIMUser;
use App\Libraries\Decorator\Image\CoverDecorator;
use App\Libraries\Decorator\Tool\IsEndDecorator;
use App\Libraries\Decorator\User\UserDecorator;
use App\Libraries\Decorator\User\UserPointDecorator;
use App\Libraries\Easemob\Easemob;
use App\Libraries\Tools\ConstVar;
use App\Libraries\Tools\Msg;
use App\Libraries\Tools\Tools;
use App\Models\Config\Config;
use App\Models\HongBao\HongBao;
use App\Models\Msg\MsgSystem;
use App\Models\Post\Post;
use App\Models\Shop\ShopFav;
use App\Models\Tool\District;
use App\Models\User\UserPwLock;
use App\Models\User\UserReport;
use App\Models\Tool\BlackList;
use App\Models\User\Address;
use App\Models\User\Follow;
use App\Models\User\SMS;
use App\Models\User\UserWithdrawConfig;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Mockery\CountValidator\Exception;
use OSS\OssClient;
use OSS\Core\OssException;

class UserController extends Controller{


    protected $users;
    protected $auth_user;
    protected $cover_decorator;
    protected $user_decorator;
    protected $isEndDecorator;

    public function __construct(User $users,
                                CoverDecorator $cover_decorator,
                                UserDecorator $user_decorator,
                                IsEndDecorator $isEndDecorator){
        $this->users = $users;
        $this->auth_user = Auth::user();
        $this->cover_decorator = $cover_decorator;
        $this->user_decorator = $user_decorator;
        $this->isEndDecorator = $isEndDecorator;
    }

    /**
     * 用户详细
     * @param $id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail($id, Request $request){
        $valid_data = $request->all();
        $valid_data['id'] = $id;
        $validator = Validator::make($valid_data, [
            'id' => 'required|integer',
            'need_manager' => 'in:0,1',
            'need_withdraw_config' => 'in:0,1'
        ], [
            'id.required' => '10001',
            'id.integer' => '10002',
            'need_manager.in' => '10002',
            'need_withdraw_config.in' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        $this->users->addDecorator($this->cover_decorator);
        $this->users->addDecorator($this->user_decorator);
        $this->users->addDecorator(new UserPointDecorator());
        $sql = $this->users->with('points')->where('user_id', $id);
        if($request['need_manager']){
            $sql = $sql->withOnly('shops', ['user_id', 'title', 'shop_id', 'level']);
        }
        $user = $sql->where('user_id', $id)
            ->where('status', 1)
            ->first();
        if(empty($user)){
            return $this->sendFailResponse(400, 40301);
        }
        $user->third_party = empty($user->open_id)?0:1;
        $user->xiaochengxu = empty($user->x_open_id)?0:1;
        $user->shop_fav = ShopFav::where('user_id', $user->user_id)->where('status', 1)->count();
        $user->posts = Post::where('user_id', $user->user_id)->where('status', 1)->count();
        if($request['need_withdraw_config']){
            $withdraw_config = UserWithdrawConfig::where('user_id', $user->user_id)->first();
            if(empty($withdraw_config)){
                $user->ratio = Config::where('key', 'user_withdraw_ratio')->first()->value;
                $user->limit = Config::where('key', 'user_withdraw_limit')->first()->value;
                $user->mlm_ratio = Config::where('key', 'mlm_withdraw_ratio')->first()->value;
                $user->mlm_limit = Config::where('key', 'mlm_withdraw_limit')->first()->value;
            }else{
                $user->ratio = $withdraw_config->ratio;
                $user->limit = $withdraw_config->limit;
                $user->mlm_ratio = $withdraw_config->mlm_ratio;
                $user->mlm_limit = $withdraw_config->mlm_limit;
            }
        }
        $this->users->after($user);
        return $this->sendSuccessResponse($user);
    }

    /**
     * 用户列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function users(Request $request){
        $validator = Validator::make($request->all(), [
            'page' => 'required|integer',
            'size' => 'required|integer',
            'type' => 'in:1',//1-关键字搜索
            'keyword' => 'required_if:type,1',
            'no_need_friends' => 'in:0,1',
        ], [
            'page.required' => '10001',
            'page.integer' => '10002',
            'size.required' => '10001',
            'size.integer' => '10002',
            'type.in' => '10002',
            'keyword.required_if' => '10001',
            'no_need_friends.in' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        $this->users->addDecorator($this->user_decorator);
        $this->users->addDecorator($this->isEndDecorator);
        $this->users->addDecorator($this->cover_decorator);
        $this->users->addDecorator(new UserPointDecorator());
        $data = $this->users->getList($request, intval($request['no_need_friends']));
        return $this->sendSuccessResponse($data);
    }

    /**
     * 修改用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws OssException
     */
    public function edit(Request $request){
        $user = $this->auth_user;
        $validator = Validator::make($request->all(), [
            'cover' => 'image',
            'nickname' => 'string|max:100|unique:users,nickname,'.$user->user_id.',user_id',
            'true_name' => 'string|max:50',
            'sex' => 'in:0,1,2,3',
            'birthday' => 'date',
            'open_id' => 'unique:users,open_id,'.$user->user_id.',user_id',
            'x_open_id' => 'unique:users,x_open_id,'.$user->user_id.',user_id',
            'access_token' => 'required_with:open_id',
            'mobile' => ['regex:/^1[34578][0-9]{9}$/','unique:users,mobile,'.$user->user_id.',user_id'],
            'code' => 'required_with:mobile|size:4',
            'district_id' => 'integer',
            'longitude' => 'numeric',
            'latitude' => 'numeric',
        ], [
            'cover.image' => '10003',
            'nickname.string' => '10002',
            'nickname.max' => '10004',
            'nickname.unique' => '10004',
            'true_name.string' => '10002',
            'true_name.max' => '10004',
            'sex.in' => '10002',
            'birthday.date' => '10005',
            'open_id.unique' => '10010',
            'x_open_id.unique' => '10010',
            'access_token.required_with' => '10001',
            'mobile.regex' => '10006',
            'mobile.unique' => '10007',
            'code.required_with' => '10001',
            'code.size' => '10002',
            'district_id.integer' => '10002',
            'longitude.numeric' => '10002',
            'latitude.numeric' => '10002',
        ]);

        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }

        if(!empty($request['nickname'])){
            $request['nickname'] = Tools::removeXSS($request['nickname']);
        }

        if(!empty($request['true_name'])){
            $request['true_name'] = Tools::removeXSS($request['true_name']);
        }
        //头像
        if($request->hasFile('cover') && $request->file('cover')->isValid()){
            try{
                $ossClient = new OssClient(env('ALIYUN_ID'), env('ALIYUN_KEY'), env('ALIYUN_ENDPOINT'));
                $bucket = env('ALIYUN_BUCKET');
                $object = 'image/avatar_'.$user->user_id.'_'.time().'.'.$request->file('cover')->extension();
                $ossClient->uploadFile($bucket, $object, $request->file('cover')->getFileInfo());
                $user->cover = $object;
            }catch (Exception $e){
                return $this->sendFailResponse(400,40003);
            }
        }

        //昵称
        if(!empty($request['nickname'])){
            $user->nickname = preg_replace('/\s/', '', $request['nickname']);
            if($this->users->checkNicknameExist($user->nickname, $user->mobile)){
                return $this->sendFailResponse(400, 10004);
            }
//            Easemob::singleton()->editNickname($user->user_id, $user->nickname);
        }

        //真名
        if(!empty($request['true_name'])){
            $user->true_name = $request['true_name'];
        }

        //性别
        if(isset($request['sex'])){
            $user->sex = $request['sex'];
        }

        //生日
        if(!empty($request['birthday'])){
            $user->birthday = strtotime($request['birthday']);
        }

        //手机
        if(isset($request['mobile']) && isset($request['code'])){
            $sms = new SMS();
            $code = $sms->checkCode($request['mobile'], $request['code']);
            if(!$code){
                return $this->sendFailResponse(400,40002);
            }
            $user->mobile = $request['mobile'];
            $code->status = 1;
            $code->save();
        }

        //绑定第三方登录
        if(isset($request['open_id']) && isset($request['access_token'])){
            $user->open_id = $request['open_id'];
        }

        //绑定小程序登录
        if(isset($request['x_open_id']) && isset($request['access_token'])){
            $user->x_open_id = $request['x_open_id'];
        }

        //登录位置 地区ID
        if(!empty($request['district_id'])){
            $user->district_id = $request['district_id'];
        }

        //登录位置 经纬度
        if(!empty($request['longitude']) && !empty($request['latitude'])){
            $user->longitude = $request['longitude'];
            $user->latitude = $request['latitude'];
        }
        $user->save();
        dispatch(new GetMobileCityIdJob($user->user_id));
        dispatch(new UpdateIMUser($user));
        $user->third_party = empty($user->open_id)?0:1;
        $user->xiaochengxu = empty($user->x_open_id)?0:1;
        $user->addDecorator($this->cover_decorator);
        $user->addDecorator($this->user_decorator);
        $user = $user->after($user);
        return $this->sendSuccessResponse($user);
    }

    /**
     * 检查昵称
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkNickname(Request $request){
        $user = $this->auth_user;
        $validator = Validator::make($request->all(), [
            'nickname' => 'string|max:100|unique:users,nickname,'.$user->user_id.',user_id',
        ], [
            'nickname.string' => '10002',
            'nickname.max' => '10004',
            'nickname.unique' => '10004',
        ]);

        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }

        return $this->sendSuccessResponse([]);
    }

    /**
     * 获取用户所有收货地址
     * @param Address $address
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAddresses(Address $address){
        $data = $address->getAllAddress($this->auth_user->user_id);
        return $this->sendSuccessResponse($data);
    }

    /**
     * 添加收货地址
     * @param Address $address
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addAddress(Address $address, Request $request){
        $validator = Validator::make($request->all(), [
            'province_id' => 'required|integer',
            'city_id' => 'required|integer',
            'district_id' => 'required|integer',
            'mobile' => ['required', 'regex:/^1[34578][0-9]{9}$/'],
            'address' => 'required|string|max:500',
            'name' => 'required|string|max:20',
        ], [
            'province_id.required' => '10001',
            'province_id.integer' => '10002',
            'city_id.required' => '10001',
            'city_id.integer' => '10002',
            'district_id.required' => '10001',
            'district_id.integer' => '10002',
            'mobile.required' => '10001',
            'mobile.regex' => '10002',
            'address.required' => '10001',
            'address.string' => '10002',
            'address.max' => '10002',
            'name.required' => '10001',
            'name.string' => '10002',
            'name.max' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }

        if(!empty($request['name'])){
            $request['name'] = Tools::removeXSS($request['name']);
        }
        if(!empty($request['address'])){
            $request['address'] = Tools::removeXSS($request['address']);
        }

        $address->user_id = $this->auth_user->user_id;
        $address->mobile = $request['mobile'];
        $address->name = $request['name'];
        $address->province_id = $request['province_id'];
        $address->city_id = $request['city_id'];
        $address->district_id = $request['district_id'];
        $address->address = $request['address'];
        $address->save();
        return $this->sendSuccessResponse($address);
    }

    /**
     * 修改地址
     * @param Address $address
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function editAddress(Address $address, Request $request, $id){
        $validator = Validator::make($request->all(), [
            'province_id' => 'required|integer',
            'city_id' => 'required|integer',
            'district_id' => 'required|integer',
            'mobile' => ['required', 'regex:/^1[34578][0-9]{9}$/'],
            'address' => 'required|string|max:500',
            'name' => 'required|string|max:20',
        ], [
            'province_id.required' => '10001',
            'province_id.integer' => '10002',
            'city_id.required' => '10001',
            'city_id.integer' => '10002',
            'district_id.required' => '10001',
            'district_id.integer' => '10002',
            'mobile.required' => '10001',
            'mobile.regex' => '10002',
            'address.required' => '10001',
            'address.string' => '10002',
            'address.max' => '10002',
            'name.required' => '10001',
            'name.string' => '10002',
            'name.max' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        if(!empty($request['name'])){
            $request['name'] = Tools::removeXSS($request['name']);
        }
        if(!empty($request['address'])){
            $request['address'] = Tools::removeXSS($request['address']);
        }

        $id = abs(intval($id));
        $data = $address->findOrFail($id);
        $data->user_id = $this->auth_user->user_id;
        $data->province_id = $request['province_id'];
        $data->city_id = $request['city_id'];
        $data->district_id = $request['district_id'];
        $data->mobile = $request['mobile'];
        $data->name = $request['name'];
        $data->address = $request['address'];
        $data->save();
        return $this->sendSuccessResponse($data);
    }

    /**
     * 删除地址
     * @param $id
     * @param Address $address
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteAddress($id, Address $address){
        $validator = Validator::make(['id'=>$id], [
            'id' => 'required|integer',
        ], [
            'id.required' => '10001',
            'id.integer' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        if($address->where('id', $id)->where('user_id', Auth::id())->delete()){
            return $this->sendSuccessResponse([]);
        }
        return $this->sendFailResponse(400, 40101);
    }

    /**
     * 设置默认地址
     * @param Address $address
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function setDefaultAddress(Address $address, $id){
        $id = abs(intval($id));
        $address->setDefault($this->auth_user->user_id, $id);
        return $this->sendSuccessResponse([]);
    }

    /**
     * 设置/重置密码
     * @param Request $request
     * @param SMS $sms
     * @return \Illuminate\Http\JsonResponse
     */
    public function setPassword(Request $request, SMS $sms){
        $validator = Validator::make($request->all(), [
            'mobile' => ['regex:/^1[34578][0-9]{9}$/','required','exists:users,mobile'],
            'code' => 'required_with:mobile|size:4',
            'password' => 'required|string|min:6',
            're_password' => 'same:password'
        ], [
            'mobile.required' => '10001',
            'mobile.regex' => '10006',
            'mobile.exists' => '40302',
            'code.required_with' => '10001',
            'code.size' => '10002',
            'password.required' => '10001',
            'password.string' => '10002',
            'password.min' => '10008',
            're_password.same' => '10009',
        ]);

        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }

        $code = $sms->checkCode($request['mobile'], $request['code']);
        if(empty($code)){
            return $this->sendFailResponse(400, 40002);
        }

        $code->status = 1;
        $code->save();
        $user = $this->users->getUserObjectByOpenIdOrMobile($request['mobile']);
        $user->password = password_hash($request['password'], PASSWORD_DEFAULT);
        $user->save();
        UserPwLock::updateOrCreate(['user_id'=>$user->user_id], ['login_pw'=>0]);
        return $this->sendSuccessResponse([]);
    }

    /**
     * 设置/重置密码
     * @param Request $request
     * @param SMS $sms
     * @return \Illuminate\Http\JsonResponse
     */
    public function setPaymentPw(Request $request, SMS $sms){
        $validator = Validator::make($request->all(), [
            'mobile' => ['regex:/^1[34578][0-9]{9}$/','required','exists:users,mobile'],
            'code' => 'required_with:mobile|size:4',
            'password' => 'required|digits:6',
            're_password' => 'same:password'
        ], [
            'mobile.required' => '10001',
            'mobile.regex' => '10006',
            'mobile.exists' => '40302',
            'code.required_with' => '10001',
            'code.size' => '10002',
            'password.required' => '10001',
            'password.digits' => '10002',
            're_password.same' => '10009',
        ]);

        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        $code = $sms->checkCode($request['mobile'], $request['code']);
        if(empty($code)){
            return $this->sendFailResponse(400, 40002);
        }

        $code->status = 1;
        $code->save();
        $user = $this->users->getUserObjectByOpenIdOrMobile($request['mobile']);
        if($user->user_id != Auth::id()){
            return $this->sendFailResponse(400, 40001);
        }
        $user->payment_pw = password_hash($request['password'], PASSWORD_DEFAULT);
        $user->save();
        UserPwLock::updateOrCreate(['user_id'=>$user->user_id], ['payment_pw'=>0]);
        return $this->sendSuccessResponse([]);
    }

    /**
     * 获取用户统计数据
     * @param $id
     * @param Follow $follow
     * @param Post $post
     * @param HongBao $hongBao
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserSta($id, Follow $follow, Post $post, HongBao $hongBao){
        $valid_data['id'] = $id;
        $validator = Validator::make($valid_data, [
            'id' => 'required|integer',
        ], [
            'id.required' => '10001',
            'id.integer' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        $data = [];
        $follow_data = $follow->where('user_id', Auth::id())->where('follow_id', $id)->where('status', 1)->first();
        if(empty($follow_data)){
            $data['is_follow'] = 0;
        }else{
            $data['is_follow'] = 1;
        }
        $data['follow'] = $follow->where('user_id', $id)->where('status', 1)->count();
        $data['follower'] = $follow->where('follow_id', $id)->where('status', 1)->count();
        $data['post'] = $post->where('user_id', $id)->where('status', 1)->count();
        $data['hong_bao'] = $hongBao->where('user_id', $id)->where('status', 0)->where('end_at', '>=', time())->count();
        return $this->sendSuccessResponse($data);
    }

    /**
     * 关注列表
     * @param $id
     * @param Follow $follow
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getFollow($id, Follow $follow, Request $request){
        $valid_data = $request->all();
        $valid_data['id'] = $id;
        $validator = Validator::make($valid_data, [
            'id' => 'required|integer',
            'page' => 'required|integer',
            'size' => 'required|integer',
        ], [
            'id.required' => '10001',
            'id.integer' => '10002',
            'page.required' => '10001',
            'page.integer' => '10002',
            'size.required' => '10001',
            'size.integer' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        $follow->addDecorator($this->cover_decorator);
        $follow->addDecorator($this->isEndDecorator);
        $data = $follow->followList($id, $request['page'], $request['size']);
        return $this->sendSuccessResponse($data);
    }

    /**
     * 粉丝列表
     * @param $id
     * @param Follow $follow
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getFollower($id, Follow $follow, Request $request){
        $valid_data = $request->all();
        $valid_data['id'] = $id;
        $validator = Validator::make($valid_data, [
            'id' => 'required|integer',
            'page' => 'required|integer',
            'size' => 'required|integer',
        ], [
            'id.required' => '10001',
            'id.integer' => '10002',
            'page.required' => '10001',
            'page.integer' => '10002',
            'size.required' => '10001',
            'size.integer' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        $follow->addDecorator($this->cover_decorator);
        $follow->addDecorator($this->isEndDecorator);
        $data = $follow->followerList($id, $request['page'], $request['size']);
        return $this->sendSuccessResponse($data);
    }

    /**
     * 关注
     * @param $id
     * @param Follow $follow
     * @return \Illuminate\Http\JsonResponse
     */
    public function follow($id, Follow $follow){
        $valid_data['id'] = $id;
        $validator = Validator::make($valid_data, [
            'id' => 'required|integer',
        ], [
            'id.required' => '10001',
            'id.integer' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        $user_id = Auth::id();
        $follow_data = $follow->firstOrCreate(['user_id'=>$user_id, 'follow_id'=>$id]);
        $follow_data->status = intval($follow_data->status XOR 1);
        $follow_data->save();
        return $this->sendSuccessResponse(['status'=>$follow_data->status]);
    }

    /**
     * 拉黑
     * @param $id
     * @param BlackList $blackList
     * @return \Illuminate\Http\JsonResponse
     */
    public function blackList($id, BlackList $blackList){
        $valid_data['id'] = $id;
        $validator = Validator::make($valid_data, [
            'id' => 'required|integer',
        ], [
            'id.required' => '10001',
            'id.integer' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        $user_id = Auth::id();
        if($user_id == $id){
            return $this->sendFailResponse(400, 40001);
        }
        $black_list = $blackList->firstOrCreate([
            'user_id' => $user_id,
            'black_id' => $id,
        ]);
        $black_list->status = intval($black_list->status XOR 1);
        $black_list->save();
        return $this->sendSuccessResponse(['status'=>$black_list->status]);
    }

    /**
     * 投诉
     * @param $id
     * @param UserReport $userReport
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function report($id, UserReport $userReport, Request $request){
        $valid_data = $request->all();
        $valid_data['id'] = $id;
        $validator = Validator::make($valid_data, [
            'id' => 'required|integer',
            'reason' => 'string|max:200',
        ], [
            'id.required' => '10001',
            'id.integer' => '10002',
            'reason.string' => '10002',
            'reason.max' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        $user_id = Auth::id();
        $report = $userReport->firstOrCreate([
            'from_id' => $user_id,
            'to_id' => $id,
            'status'  => 0,
        ]);
        $report->reason = empty($request['reason'])?'':$request['reason'];
        $report->save();
        return $this->sendSuccessResponse([]);
    }

    /**
     * 管理员修改用户
     * @param $id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function adminEdit($id, Request $request){
        $valid_data = $request->all();
        $valid_data['id'] = $id;
        $validator = Validator::make($valid_data, [
            'id' => 'required|integer',
            'auth' => 'required|in:0,1',
            'agent' => 'in:0,1',
            'agent_city_id' => 'required_if:agent,1|integer',
        ], [
            'id.required' => '10001',
            'id.integer' => '10002',
            'auth.required' => '10001',
            'auth.in' => '10002',
            'agent.in' => '10002',
            'agent_city_id.required_if' => '10001',
            'agent_city_id.integer' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }

        if(empty($this->auth_user->is_admin)){//判断admin
            return $this->sendFailResponse(400, 40101);
        }

        $user = $this->users->where('user_id', $id)->first();
        if(!isset($request['agent'])){
            $request['agent'] = $user->is_agent;
            $request['agent_city_id'] = 0;
        }
        if($user->is_auth != $request['auth']){
            $msg = $request['auth']?Msg::auth_earn():Msg::auth_lose();
            $ext = ['user_id'=>6, 'type'=>ConstVar::$IM_MSG_AUTH_CHANGE, 'auth'=>$request['auth']];
            dispatch(new SendSystemMsgJob([$id], $msg, ConstVar::$IM_MSG_AUTH_CHANGE, $ext));
        }
        if($user->is_agent != $request['agent']){
            $msg = $request['agent']?Msg::agent_earn():Msg::agent_lose();
            $ext = ['user_id'=>6, 'type'=>ConstVar::$IM_MSG_AUTH_CHANGE, 'agent'=>$request['agent']];
            dispatch(new SendSystemMsgJob([$id], $msg, ConstVar::$IM_MSG_AGENT_CHANGE, $ext));
        }

        $this->users->where('user_id', $id)->update([
            'is_auth'=>$request['auth'],
            'is_agent'=>$request['agent'],
            'agent_city_id'=>$request['agent_city_id'],
        ]);

        return $this->sendSuccessResponse([
            'is_auth'=>$request['auth'],
            'is_agent'=>$request['agent']
        ]);
    }

    /**
     * 代理修改用户
     * @param $id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function agentEdit($id, Request $request){
        $valid_data = $request->all();
        $valid_data['id'] = $id;
        $validator = Validator::make($valid_data, [
            'id' => 'required|integer',
            'auth' => 'required|in:0,1',
        ], [
            'id.required' => '10001',
            'id.integer' => '10002',
            'auth.required' => '10001',
            'auth.in' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }

        if(empty($this->auth_user->is_agent)){//判断admin
            return $this->sendFailResponse(400, 40101);
        }

        $user = $this->users->where('user_id', $id)->first();
        if($user->mobile_city_id != $this->auth_user->agent_city_id){
            return $this->sendFailResponse(400, 40101);
        }
        if($user->is_auth != $request['auth']){
            $msg = $request['auth']?Msg::auth_earn():Msg::auth_lose();
            dispatch(new SendSystemMsgJob([$id], $msg, ConstVar::$IM_MSG_AUTH_CHANGE));
        }

        $this->users->where('user_id', $id)->update([
            'is_auth'=>$request['auth']
        ]);

        return $this->sendSuccessResponse([
            'is_auth'=>$request['auth']
        ]);
    }

    /**
     * 推荐同城好友
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function recFriends(Request $request){
        $validator = Validator::make($request->all(), [
            'city_id' => 'required',
            'page' => 'required|integer',
            'size' => 'required|integer',
        ], [
            'city_id.required' => '10001',
            'page.required' => '10001',
            'page.integer' => '10002',
            'size.required' => '10001',
            'size.integer' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }

        if(Auth::user()->vip_level != 2){
            return $this->sendFailResponse(400, 40101);
        }

        $districts = District::select(['id'])->where('parent_id', $request['city_id'])->get()->toArray();
        if(empty($districts)){
            return $this->sendFailResponse(400, 40400);
        }

        $request['type'] = 2;
        $request['districts'] = $districts;
        $this->users->addDecorator($this->cover_decorator);
        $this->users->addDecorator($this->isEndDecorator);
        $data = $this->users->getList($request, true);
        return $this->sendSuccessResponse($data);
    }
}